
# coding:utf-8

from lib import flux, al, pymunk
from lib.fluxext import ViewGroup
from views.bullet import PlayerBullet
from system import phy
from utils import dir2vec, dirs2vec
from utils.suger import *
from views.unit import Unit
from utils.unit_attr import HeroAttr


class Player(Unit):
    def __init__(self, spd=100, force=1000, last_dir=al.KEY_RIGHT):
        super(Player, self).__init__(spd, force, (40, 40), last_dir, HeroAttr)

        self.bullet_type = PlayerBullet

        sprite = flux.View()
        sprite.SetAnchor(self.anchor)
        sprite.SetSize(37,60)
        sprite.SetColor(1,0,0)
        self.sprite = sprite

        def OnFire():
            #if not self.dir_stack:
            self.body.velocity.x *= 0.7
            self.body.velocity.y *= 0.7

        self.t = flux.Timer(0.3)
        self.t.OnFire = OnFire
        self.t.Start()

        self.skill.learn(1)
        self.skill.learn(2)
        self.skill.learn(3)
        self.skill.learn(4)

        @smokesignal.on('game_continue')
        @smokesignal.on('game_pause')
        def _callback():
            self.PauseCheck()

    def GetSize(self):
        return self.sprite.GetSize()

    def ApplyPhy(self):
        pos = self.GetPos()
        size = self.sprite.GetSize()
        body = pymunk.Body(1, pymunk.inf)
        body.position = pymunk.vec2d.Vec2d(pos.x, pos.y)
        body.velocity_limit = self.attr.spd

        #poly = pymunk.Poly.create_box(body, (size.x, size.y))
        s = pymunk.Circle(body, size.x/2)
        s.group = phy.GROUP_PLAYER
        s.layers = pow(2, 1) | pow(2, 2)
        phy.space.add(body, s)

        self.body = body
        phy.Reg(body, self)

    def PauseCheck(self):
        # 目前a5的al_get_keyboard_state存在BUG
        # https://www.allegro.cc/forums/thread/610437
        # 在恢复时不能正确读出按键状态，故暂停后直接重置。我觉得效果勉勉强强吧。
        self.dir_stack = []
        self.body.reset_forces()
        self.body.velocity = 0,0
        return

        for i in self.dir_stack:
            if not flux.IsKeyDown(i):
                self.dir_stack.remove(i)
        self.body.reset_forces()
        self.body.velocity = 0,0
        self.body.apply_force(dirs2vec(self.dir_stack, self.force))

    def Move(self, key):
        self.dir_stack.append(key)
        self.body.reset_forces()
        self.body.apply_force(dir2vec(self.dir_stack[-1] if self.dir_stack else [], self.attr.force))

    def UnMove(self, key):
        if not key in self.dir_stack:
            return
        self.dir_stack.remove(key)
        if not self.dir_stack:
            self.last_dir = key

        self.body.reset_forces()
        self.body.velocity = 0,0
        self.body.apply_force(dir2vec(self.dir_stack[-1] if self.dir_stack else [], self.attr.force))

    # 获取面朝方向
    def GetDir(self):
        if self.dir_stack:
            return self.dir_stack[-1]
        else:
            return self.last_dir
